package com.ck.company.controller;

import com.ck.chuangke.controller.CkProgramController;
import com.ck.chuangke.service.CkProgramService;
import com.ck.company.service.CpDeviceGroupService;
import com.ck.company.service.CpDeviceInfoService;
import com.ck.company.service.CpProgramService;
import com.ck.constant.DateFormatConstant;
import com.ck.constant.PageConstant;
import com.ck.constant.RequestConstant;
import com.ck.export.util.SimpleExportUtil;
import com.ck.model.chuangke.vo.CkProgramListVO;
import com.ck.model.common.User;
import com.ck.model.company.dto.CpDeviceGroupListDTO;
import com.ck.model.company.vo.CpAllDeviceVO;
import com.ck.model.company.vo.CpAllProgramExportVO;
import com.ck.model.company.vo.CpSingleDeviceVO;
import com.ck.model.company.vo.CpSingleProgramVO;
import com.ck.util.DateUtils;
import com.github.pagehelper.Page;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;

/**
 * @ClassName CpReportController
 * @Description 商家管理后台-统计报表
 * @Author HanQinrui
 * @Date 2018/7/9 16:46
 * @Version 1.0p
 **/
@Controller
@RequestMapping(value = "/cpReport")
public class CpReportController{
    private Logger logger = LoggerFactory.getLogger(CkProgramController.class);
    @Autowired
    CkProgramService ckProgramService;
    @Autowired
    private CpProgramService cpProgramService;
    @Autowired
    private CpDeviceInfoService cpDeviceInfoService;
    @Autowired
    private CpDeviceGroupService deviceGroupService;
    /**
     * 全部节目分页列表
     * @param programStatus 节目状态 0：已审批，1：待审批，2：待发布，3：已过期
     * @param programName   节目名称
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param model 模型
     * @param pageNum 当前页数
     * @param pageSize 每页条数
     * @param request 请求
     * @return
     */
    @RequestMapping(value = "/allProgramReport")
    public Object allProgramReport(Integer programStatus, String programName, String startTime, String endTime, Model model,
                                   Integer pageNum, Integer pageSize, HttpServletRequest request) {
        try {
            pageNum = (pageNum == null ? PageConstant.DEFAULT_PAGE_NUM : pageNum);
            pageSize = (pageSize == null ? PageConstant.DEFAULT_PAGE_SIZE : pageSize);
            // 获取当前登录的商家代码
            User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
            String companyCode = loginUser.getCompanyCode();
            //把格式化字符串时间转化为Long类型时间戳
            Long startTimeL = null;
            Long endTimeL = null;
            try {
                if (StringUtils.isNotBlank(startTime)) {
                    startTimeL = DateUtils.stringTimeToLongTimeStamp(startTime, DateFormatConstant.LONG_DATE_FORMAT_STR);
                }
                if (StringUtils.isNotBlank(endTime)) {
                    endTimeL = DateUtils.stringTimeToLongTimeStamp(endTime, DateFormatConstant.LONG_DATE_FORMAT_STR);
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
            Page<CkProgramListVO> page = cpProgramService.allProgramList(programStatus, companyCode, programName, startTimeL, endTimeL, pageNum, pageSize);
            model.addAttribute("pageNum", page.getPageNum());
            model.addAttribute("pageSize", page.getPageSize());
            model.addAttribute("result", page.getResult());
            model.addAttribute("total", page.getTotal());
            model.addAttribute("programStatus", programStatus);
            model.addAttribute("companyCode", companyCode);
            model.addAttribute("programName", programName);
            model.addAttribute("startTime", startTime);
            model.addAttribute("endTime", endTime);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("CpReportController allProgramReport 查询全部节目报表失败:" + e.getMessage());
        }
        return "cp/cp_all_program_report";
    }

    /**
     * 导出全部节目报表
     * @param programStatus 节目状态 0：已审批，1：待审批，2：待发布，3：已过期
     * @param programName 节目名称
     * @param dateRange 时间范围
     * @param request
     * @return
     */
    @RequestMapping(value = "/allProgramExport")
    public void allProgramExport(Integer programStatus, String programName, String dateRange,
                                   HttpServletRequest request, HttpServletResponse response){
        try(OutputStream out = response.getOutputStream()) {
            // 获取当前登录的商家代码
            User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
            String companyCode = loginUser.getCompanyCode();
            Long startTime = null;
            Long endTime = null;
            // 处理时间范围
            if(StringUtils.isNotBlank(dateRange)) {
                HashMap<Object, Long> dateMap = DateUtils.dateRangeToString(dateRange, DateUtils.PATTEN_YMD1);
                startTime = dateMap.get("startTime");
                endTime = dateMap.get("endTime");
            }
            List<CpAllProgramExportVO> cpAllProgramExportVO = cpProgramService.allProgramListExport(programStatus, companyCode, programName, startTime, endTime);
            //设置输出类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //设置文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("全部节目.xls").getBytes(), "ISO-8859-1"));
            SimpleExportUtil.exportToExcel(cpAllProgramExportVO, "全部节目").write(out);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("CpReportController allProgramExport 导出全部节目报表失败:" + e.getMessage());
        }
    }

    /**
     * 单个节目分页列表
     * @param programName 节目名称
     * @param programId 节目ID
     * @param model 模型
     * @param pageNum 当前页数
     * @param pageSize 每页条数
     * @param request
     * @return
     */
    @RequestMapping(value = "/singleProgramReport")
    public Object singleProgramReport(String programName, String programId, Model model,
                                      Integer pageNum, Integer pageSize, HttpServletRequest request) {
        // 查询条件：节目名称和节目ID都为空时，默认不查询
        if (StringUtils.isBlank(programId) && StringUtils.isBlank(programName)) {
            model.addAttribute("total", 0);
            model.addAttribute("pageNum", PageConstant.DEFAULT_PAGE_NUM);
            model.addAttribute("pageSize", PageConstant.DEFAULT_PAGE_SIZE);
            return "cp/cp_single_program_report";
        }
        // 获取当前登录的商家代码
        User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
        String companyCode = loginUser.getCompanyCode();
        Page<CpSingleProgramVO> page = cpProgramService.singleProgramList(companyCode, programName, programId, pageNum, pageSize);
        model.addAttribute("programName", programName);
        model.addAttribute("programId", programId);
        model.addAttribute("pageNum", page.getPageNum());
        model.addAttribute("pageSize", page.getPageSize());
        model.addAttribute("result", page.getResult());
        model.addAttribute("total", page.getTotal());
        return "cp/cp_single_program_report";
    }

    /**
     * 单个节目列表导出
     * @param programName 节目名称
     * @param programId 节目ID
     * @param request
     * @param response
     */
    @RequestMapping(value = "/singleProgramExport")
    public void singleProgramExport(String programName, String programId, HttpServletRequest request, HttpServletResponse response) {
        try(OutputStream out = response.getOutputStream()) {
            // 获取当前登录的商家代码
            User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
            String companyCode = loginUser.getCompanyCode();
            List<CpSingleProgramVO> cpSingleProgramVO = null;
            // 查询条件：节目名称和节目ID都为空时，默认不查询
            if (StringUtils.isBlank(programId) && StringUtils.isBlank(programName)) {
                cpSingleProgramVO = Lists.newArrayList();
            } else {
                cpSingleProgramVO = cpProgramService.singleProgramListExport(companyCode, programId, programName);
            }
            //设置输出类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //设置文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("单个节目.xls").getBytes(), "ISO-8859-1"));
            SimpleExportUtil.exportToExcel(cpSingleProgramVO, "单个节目").write(out);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("CpReportController singleProgramExport 导出单个节目报表失败:" + e.getMessage());
        }
    }


    /**
     * 全部终端分页列表
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param province 省
     * @param city 市
     * @param area 区
     * @param deviceCode 机器码
     * @param deviceMac 终端Mac
     * @param deviceGroup 终端所属分组
     * @param model 模型
     * @param pageNum 当前页数
     * @param pageSize 每页条数
     * @return
     */
    @RequestMapping(value = "/allDeviceReport")
    public Object allDeviceReport(String startTime, String endTime, String province, String city, String area,
                                  String deviceCode, String deviceMac, String deviceGroup,
                                  Model model, Integer pageNum, Integer pageSize, HttpServletRequest request) {
        try {
            // 获取当前登录的商家代码
            User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
            String companyCode = loginUser.getCompanyCode();
            Page<CpAllDeviceVO> page = cpDeviceInfoService.allDeviceReport(startTime, endTime, province, city, area, deviceCode, deviceMac, deviceGroup, companyCode, pageNum, pageSize);
            model.addAttribute("startTime", startTime);
            model.addAttribute("endTime", endTime);
            model.addAttribute("province", province);
            model.addAttribute("city", city);
            model.addAttribute("area", area);
            model.addAttribute("deviceCode", deviceCode);
            model.addAttribute("deviceMac", deviceMac);
            model.addAttribute("deviceGroup", deviceGroup);
            model.addAttribute("pageNum", page.getPageNum());
            model.addAttribute("pageSize", page.getPageSize());
            model.addAttribute("total", page.getTotal());
            model.addAttribute("result", page.getResult());
            //分组下拉
            List<CpDeviceGroupListDTO> deviceGroupListDTOList = deviceGroupService.listAllDeviceGroup(companyCode);
            model.addAttribute("deviceGroupListDTOList", deviceGroupListDTOList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("CpReportController allDeviceReport 查询全部终端报表失败:" + e.getMessage());
        }
        return "cp/cp_all_device";
    }


    /**
     * 全部终端列表导出
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param province 省
     * @param city 市
     * @param area 区
     * @param deviceCode 机器码
     * @param deviceMac 终端Mac
     * @param deviceGroup 终端所属分组
     * @param request
     * @param response
     */
    @RequestMapping(value = "/allDeviceExport")
    public void allDeviceExport(String startTime, String endTime, String province, String city, String area,
                                String deviceCode, String deviceMac, String deviceGroup,
                                HttpServletRequest request, HttpServletResponse response) {
        try(OutputStream out = response.getOutputStream()) {
            // 获取当前登录的商家代码
            User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
            String companyCode = loginUser.getCompanyCode();
            List<CpAllDeviceVO> cpAllDeviceVO = cpDeviceInfoService.allDeviceListExport(companyCode, startTime ,endTime, province, city, area, deviceCode, deviceMac, deviceGroup);
            //设置输出类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //设置文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("全部终端.xls").getBytes(), "ISO-8859-1"));
            SimpleExportUtil.exportToExcel(cpAllDeviceVO, "全部终端").write(out);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("CpReportController allDeviceExport 导出全部终端列表失败:" + e.getMessage());
        }
    }


    /**
     * 单个终端分页列表
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param deviceCode 机器码
     * @param deviceMac 终端MAC
     * @param model 模型
     * @param pageNum 当前页数
     * @param pageSize 每页条数
     * @param request
     * @return
     */
    @RequestMapping(value = "/singleDeviceReport")
    public Object singleDeviceReport(String startTime, String endTime, String deviceCode, String deviceMac,
                                  Model model, Integer pageNum, Integer pageSize, HttpServletRequest request) {
        try {
            // 查询条件：机器码和终端MAC都为空时，默认不查询
            if (StringUtils.isBlank(deviceCode) && StringUtils.isBlank(deviceMac)) {
                model.addAttribute("total", 0);
                model.addAttribute("pageNum", PageConstant.DEFAULT_PAGE_NUM);
                model.addAttribute("pageSize", PageConstant.DEFAULT_PAGE_SIZE);
                return "cp/cp_single_device";
            }
            // 获取当前登录的商家代码
            User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
            String companyCode = loginUser.getCompanyCode();
            Page<CpSingleDeviceVO> page = cpDeviceInfoService.singleDeviceReport(startTime, endTime, deviceCode, deviceMac, companyCode, pageNum, pageSize);
            model.addAttribute("startTime", startTime);
            model.addAttribute("endTime", endTime);
            model.addAttribute("deviceCode", deviceCode);
            model.addAttribute("deviceMac", deviceMac);
            model.addAttribute("pageNum", page.getPageNum());
            model.addAttribute("pageSize", page.getPageSize());
            model.addAttribute("total", page.getTotal());
            model.addAttribute("result", page.getResult());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("CpReportController singleDeviceReport 查询单个终端报表失败:" + e.getMessage());
        }
        return "cp/cp_single_device";
    }

    /**
     * 单个终端报表导出
     * @param startTime
     * @param endTime
     * @param deviceCode
     * @param deviceMac
     * @param request
     * @param response
     */
    @RequestMapping(value = "/singleDeviceExport")
    public void singleDeviceExport(String startTime, String endTime, String deviceCode, String deviceMac,
                                   HttpServletRequest request, HttpServletResponse response) {
        try(OutputStream out = response.getOutputStream()) {
            // 获取当前登录的商家代码
            User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
            String companyCode = loginUser.getCompanyCode();
            List<CpSingleDeviceVO> cpSingleDeviceVO = cpDeviceInfoService.singleDeviceListExport(companyCode, startTime ,endTime, deviceCode, deviceMac);
            //设置输出类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //设置文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("单个终端.xls").getBytes(), "ISO-8859-1"));
            SimpleExportUtil.exportToExcel(cpSingleDeviceVO, "单个终端").write(out);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("CpReportController singleDeviceExport 导出单个终端列表失败:" + e.getMessage());
        }
    }
}
